package com.health.es.config;

import com.health.es.annotation.EnableEsInit;
import com.health.es.temp.EsClassOperations;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @author nqlz
 */
public class EsInitRegister implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes attributes = AnnotationAttributes
                .fromMap(importingClassMetadata.getAnnotationAttributes(EnableEsInit.class.getName()));
        assert attributes != null;
        String[] basePackages = attributes.getStringArray("packageName");
        Class<?>[] basePackageClasses = attributes.getClassArray("value");
        Set<String> packagesToScan = new LinkedHashSet<>(Arrays.asList(basePackages));
        for (Class<?> basePackageClass : basePackageClasses) {
            packagesToScan.add(ClassUtils.getPackageName(basePackageClass));
        }
        EsClassOperations.packageNames = packagesToScan;
        //通过FactoryBean去动态生成接口的代理对象
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(EsInit.class);
        AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
        //将beanDefinition注册到容器中
        registry.registerBeanDefinition("esInit", beanDefinition);
    }
}
